<?php

namespace Admin\Controller;

use Base\BackController;

class LooksController extends BackController {

    //用户列表
    public function index() {
        // echo 1;
        $this->user_model = M('bh_looks');
        $join = 'left join eosi_weixin_user ON eosi_bh_looks.uid = eosi_weixin_user.id';
        $joinad ='left join eosi_bh_label ON eosi_bh_looks.label = eosi_bh_label.id';
       
        $this->status_arr= array(
            '0' => '无效',
            '1' => '有效'
        );
        //perry add 2016-06-23 如果当前用户不是admin,则只能查看自己的信息
        $map=array();
        // if($this->back_user_id!=1){
        //     $map['id']=$this->back_user_id;
        // }
        if($_GET['recommend'] == 1){
            $map['uid'] = array('in',C('super_style_uid'));
        }
        else if($_GET['recommend'] == 2){ 
            $map['uid'] = array('not in',C('super_style_uid'));
        }
        if($_GET['nicknamex']!=''){
            $map['nickname']=array('like', '%'.$_GET['nicknamex'].'%');
        }
        if($_GET['bname']!=''){
             $map['eosi_bh_label.id']=$_GET['bname'];
        }  
        if($_GET['aname']!=''){
             $map['eosi_bh_looks.name']=array('like', '%'.$_GET['aname'].'%');
        } 
        if($_GET['memo']!=''){
             $map['eosi_bh_looks.memo']=array('like', '%'.$_GET['memo'].'%');;
        }
        if($_GET['status']!=''){
             $map['eosi_bh_looks.status']=$_GET['status'];
        }
        else {
            $_GET['status']='';
        }
        //任务总数
        $total = $this->user_model->join($join)->join($joinad)->where($map)->count();
        //每页条数
        $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        //实例化分页类
        $page = new \Admin\ORG\PageNew($total, $listRows, '');
        // if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        // }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');
        $ab ='eosi_bh_looks.name as aname,eosi_bh_label.name as bname,
              eosi_bh_looks.img as aimg,eosi_bh_label.img as bimg,
                eosi_weixin_user.nickname,eosi_bh_looks.*';
        $dataList = $this->user_model->join($join)->join($joinad)->where($map)->order('eosi_bh_looks.status desc, eosi_bh_looks.show_order desc,eosi_bh_looks.update_time desc')->limit("$page->firstRow,$page->listRows")->Field($ab)->select();

        $this->new_type =M('bh_label');
        $dataListopt =$this->new_type->select();
        //数据处理
        foreach ($dataList as $k => $value){
            $cctime=$value['create_time'];
            // cate
            if($value['cate'] ==1){
                   $value['cate'] ='用户自编造型'; 
            }else{
                   $value['cate'] ='百家好推荐造型'; 
            }
            //状态
            if ($value['status'] == 1) {
                $value['status_str'] = "<span class=\"label label-sm label-success arrowed-in\">" . $this->status_arr[$value['status']] . "</span>&nbsp;|&nbsp;&nbsp;&nbsp;<span class=\"hand icon-lock red bigger-125\" style=\"cursor: pointer;\" title=\"禁用\" index='" . $value['id'] . "' ></span>";
            }else{
                $value['status_str'] = "<span class=\"label label-sm label-info arrowed-in\">" . $this->status_arr[0] . "</span>&nbsp;|&nbsp;&nbsp;&nbsp;<span class=\"hand icon-unlock green bigger-125\" style=\"cursor: pointer;\" title=\"启用\"  index='" . $value['id'] . "' ></span>";
            }
            $value['s_img'] =  ic_getUploadImgFullPath('looks',ic_getDiffSizeImg($value['aimg'],'thumb'),$cctime); 
            $value['img'] =  ic_getUploadImgFullPath('looks',$value['aimg'],$cctime); 
            $value['create_time'] = date('Y-m-d H:i:s', $value['create_time']);
            $value['update_time'] = date('Y-m-d H:i:s', $value['update_time']);


            $dataList[$k] = $value;
            $value['item_ids'] =explode(',',$value['item_ids']);
            // var_dump($value['item_ids']);
            //只有衣橱才有造型组成元素的概念，
            // $imgchild = array();
            // $closetOrCommM=D('Home/BHCloset');
            // $imgchild=$closetOrCommM->getByPage('notsure',-1,1,1,false,1,100,'id,uid,type,img,name,memo,sub_imgs,no,price,dh_date',$value['item_ids'] );         
            // $dataList[$k]['sub_imgs_arr'] = $imgchild['pageList'];
            //end 只有衣橱才有造型组成元素的概念

            //只有造型才有附图概念
            $imgchild = array();
            if(ic_checkUnEmpty($value['sub_imgs'])){
                $value['sub_imgs'] =explode(',',$value['sub_imgs']); 
                foreach ($value['sub_imgs'] as $key => $v) {
                    $imgchild[$key]=array();
                    $imgchild[$key]['s_img'] = ic_getUploadImgFullPath('looks',ic_getDiffSizeImg($v,'thumb'),$cctime);
                    $imgchild[$key]['img'] = ic_getUploadImgFullPath('looks',$v,$cctime);
                    // $imgchild[$key] = $v;
                }
            }
            $dataList[$k]['sub_imgs_arr'] = $imgchild;
            //end 只有造型才有附图概念
        }
        // dump($dataList);
        $this->assign('_listopt', $dataListopt);
        $this->assign('_list', $dataList);
        $this->assign('bname_id', $_GET['bname']);
        $this->assign('nicknamex', $_GET['nicknamex']);
        $this->assign('recommend', $_GET['recommend']);
        $this->assign('aname', $_GET['aname']);
        $this->assign('memo', $_GET['memo']);
        $this->assign('groupName', '造型管理');
        $this->assign('moduleName', '造型列表');
        $this->assign('actionName', '造型概览');
        $this->assign('nickname',$array['nickname']);
        $this->assign('selected_status', $_GET['status']);
        $this->display();
    }


    public function status_change(){
        try {
            $type = I('type');
            $userid = I('id');
            if (empty($type) || empty($userid)) {
                $ajaxdata['info'] = '丢失参数';
                $ajaxdata['status'] = 200;
                $this->ajaxReturn($ajaxdata);
            }
            if ($type == '有效')
                $str = '启用用户';
            if ($type == '无效')
                $str = '禁用用户';
            $data = array();
            $data['id'] = $userid;
            if ($type == '有效') {
                $data['status'] = 0;
            }
            if ($type == '无效') {
                $data['status'] = 1;
            }
            $falg=M('bh_looks')->save($data); 
            if(!$falg){
                $ajaxdata['info'] = '网络故障提交失败,请稍候再试';
                $ajaxdata['status'] = 200;
                $this->ajaxReturn($ajaxdata);
            }
            $ajaxdata['info'] = 'ok';
            $ajaxdata['status'] = 1;
            $this->ajaxReturn($ajaxdata);
        } catch (Exception $exc) {
            $ajaxdata['info'] = $exc->getMessage();
            $ajaxdata['status'] = 400;
            $this->ajaxReturn($ajaxdata);
        }
    }
    //编辑规则
    public function editRule() {
        if(stripos($_SERVER['HTTP_REFERER'], "Looks/index")>0){
                ic_rememberFormerPage();
            }

            $ruleid = I('id');
            if (empty($ruleid)) {
                $this->error('缺失主键');
            }
            $join = 'left join eosi_weixin_user ON eosi_bh_looks.uid = eosi_weixin_user.id';
            $joinad ='left join eosi_bh_label ON eosi_bh_looks.label = eosi_bh_label.id';
            $ab ='eosi_bh_looks.name as aname,eosi_bh_label.name as bname,
              eosi_bh_looks.img as aimg,eosi_bh_label.img as bimg,
                eosi_weixin_user.nickname,eosi_bh_looks.*';
            $map = array();
            $map['eosi_bh_looks.id'] = $ruleid;
            $data = M('bh_looks')->join($join)->join($joinad)->where($map)->Field($ab)->find();
            // dump($data);die;
            $data['sub_img_arr']=array();
            if(ic_checkUnEmpty($data['sub_imgs'])){
                $data['sub_imgs'] =explode(',',$data['sub_imgs']);
                
                foreach ($data['sub_imgs'] as $key => &$value) {
                    $tmp=ic_getUploadImgFullPath('looks',$value,$data['create_time']);
                    $data['sub_img_arr'][]=array('url'=>$tmp,'realName'=>$value);
                    $value=$tmp;
                }
            }
            $data['img'] =  ic_getUploadImgFullPath(looks,$data['aimg'],$data['create_time']);
            if (empty($data)) {
                $this->error('数据不存在');
            }
            $this->new_type =M('bh_label');
            $dataListopt =$this->new_type->select();
            //获取该造型是否在日历中推荐到了指定日
            $calendarSM=D('Home/BHCalendar');
            $re_date=$calendarSM->findByLookId($ruleid,C('super_style_uid'));
            if($re_date){
                $re_date=sprintf("%d-%d-%d",$re_date['year'],$re_date['month'],$re_date['day']);
            }
            $this->assign('re_date', $re_date);
            $this->assign('_listopt', $dataListopt);
            $this->assign('data', $data);
            $this->assign('datasub', $data['sub_imgs']);
            $this->assign('sub_img_arr', $data['sub_img_arr']);
            $this->assign('datasubstr', implode(',', $data['sub_imgs']));
            $this->assign('groupName', '造型管理');
            $this->assign('moduleName', '造型列表');
            $this->assign('actionName', '造型编辑');
            $this->display('Looks:editRule');
        }
   //上传单品图片
    public function uploadImg() { 
       try {
            $id=I('id',false);
            // dump($id);die;
            $ctime=time();
            if(ic_isPosInt($id)){
                //是编辑的提交
                $map=array('id'=>$id);
                $exist=M('bh_looks')->where($map)->find();
                if(!$exist){
                    echo "<script>parent.art.dialog.alert('" . "待更新的数据不存在，请刷新页面重试." . "');</script>";
                    exit;
                }
                $ctime=$exist['create_time'];
            }
            // import('@.ORG.UploadFileNew');
            //导入上传类
            $upload = new \Admin\ORG\UploadFileNew();
            //设置上传文件大小
            $upload->maxSize            = 100*1024*1024;
            //设置上传文件类型
            $upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
            //设置附件上传目录
            $upload->savePath           = ic_getUploadImgServerPath('looks',$ctime);
            //设置需要生成缩略图，仅对图像文件有效
            $upload->thumb              = true;
            // 设置引用图片类库包路径
            $upload->imageClassPath     = 'Think.ImageNew';
            //设置需要生成缩略图的文件后缀
            $upload->thumbPrefix        = 'm_,s_';  //生产2张缩略图
            //设置缩略图最大宽度
            $upload->thumbMaxWidth      = '600,300';
            //设置缩略图最大高度
            $upload->thumbMaxHeight     = '700,350';
            //设置上传文件规则
            $upload->saveRule           = 'uniqid';
            //删除原图
            $upload->thumbRemoveOrigin  = false;
            if (!$upload->upload()) {
                // echo 11111;
                //捕获上传异常
                //$this->error($upload->getErrorMsg());
                //echo ($upload->getErrorMsg());
                echo "<script>parent.art.dialog.alert('" . $upload->getErrorMsg() . "');</script>";
                exit;
            } else {
                //取得成功上传的文件信息
                $uploadList = $upload->getUploadFileInfo();
                //试着删除之前上传的旧图片
                $this->deleteOld();
                //保存当前图片信息到session
                $this->saveOldFIleSession($uploadList,$ctime);
                foreach ($uploadList as $key => $value) {
                    echo "<script>
                    parent.document.getElementById('img').style.display='';
                    parent.document.getElementById('img').src='" . ic_getUploadImgFullPath('looks',$value['savename'],$ctime) . "';
                    parent.document.getElementById('p_new_pic').value='" . $value['savename'] . "';
                    </script>";
                    //如果是编辑页提交，直接保存数据表，否则会造成旧图片成为垃圾图片无法删除
                    if($exist){
                        // $oldfilePath=ic_getUploadImgServerPath('looks',$exist['create_time']);
                        $this->delMulti($exist['img'],$exist['create_time']);
                        $data=array('img'=>$value['savename'],'update_time'=>time());
                        M('bh_looks')->where($map)->save($data);
                    }
                }  
            }
        }catch (Exception $exc) {
            //返回失败信息
            echo "<script>parent.art.dialog.alert('" . $exc->getMessage() . "');</script>";
            exit;
        }
    }

    //上传造型幅图图片(多张)
    public function upload() {
        try {
            $id=I('id',false);
            $ctime=time();
            if(ic_isPosInt($id)){
                //是编辑的提交
                $map=array('id'=>$id);
                $exist=M('bh_looks')->where($map)->find();
                if(!$exist){
                    echo "<script>parent.art.dialog.alert('" . "待更新的数据不存在，请刷新页面重试." . "');</script>";
                    exit;
                }
                $ctime=$exist['create_time'];
            }
            // import('@.ORG.UploadFileNew');
            //导入上传类
            $upload = new \Admin\ORG\UploadFileNew();
            //设置上传文件大小
            $upload->maxSize            = 100*1024*1024;
            //设置上传文件类型
            $upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
            //设置附件上传目录
            $upload->savePath           = ic_getUploadImgServerPath('looks',$ctime);
            //设置需要生成缩略图，仅对图像文件有效
            $upload->thumb              = true;
            // 设置引用图片类库包路径
            $upload->imageClassPath     = 'Think.ImageNew';
            //设置需要生成缩略图的文件后缀
            $upload->thumbPrefix        = 'm_,s_';  //生产2张缩略图
            //设置缩略图最大宽度
            $upload->thumbMaxWidth      = '600,300';
            //设置缩略图最大高度
            $upload->thumbMaxHeight     = '700,350';
            //设置上传文件规则
            $upload->saveRule           = 'uniqid';
            //删除原图
            $upload->thumbRemoveOrigin  = false;
            if (!$upload->upload()) {
                //捕获上传异常
                //$this->error($upload->getErrorMsg());
                //echo ($upload->getErrorMsg());
            } else {
                //取得成功上传的文件信息
                $uploadList = $upload->getUploadFileInfo();
                $img_arr=array();
                $img_arr_with_oriNmae=array();
                foreach ($uploadList as $key => $value) {
                    $img_arr[]=$value['savename'];
                }
                //试着删除之前上传的旧图片
                $this->deleteOld();
                //保存当前图片信息到session
                $this->saveOldFIleSession($uploadList,$ctime);
                $ajaxdata['info'] = implode(',', $img_arr);
                //如果是编辑页提交，直接保存数据表，否则会造成旧图片成为垃圾图片无法删除
                if($exist){
                    // $oldfilePath=ic_getUploadImgServerPath('commodity',$exist['create_time']);
                    // $tmparr=explode(',',$exist['sub_imgs']);
                    // foreach ($tmparr as $key => $value) {
                    //     $this->delMulti($oldfilePath,$value);
                    // }
                    //如果原已有附图，则新图添加在原有附图后面
                    if($exist['sub_imgs']){
                        $ajaxdata['info']=sprintf("%s,%s",$exist['sub_imgs'],$ajaxdata['info']);
                    }
                    
                    $data=array('sub_imgs'=>$ajaxdata['info'],'update_time'=>time());
                    M('bh_looks')->where($map)->save($data);
                }
                
                $ajaxdata['status'] = 1;
                $this->ajaxReturn($ajaxdata);
                
            }

            // $img_arr = [];
            // $upload = new \Think\Upload();// 实例化上传类
            // $upload->maxSize   =     3145728 ;// 设置附件上传大小
            // $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            // $upload->rootPath  =     ic_getUploadImgServerPath('commodity',time());  //'./Public/Uploads/sub_imgs/'; // 设置附件上传根目录
            // $upload->savePath  =     ''; // 设置附件上传（子）目录
            // $upload->autoSub  =     false; // 设置附件上传（子）目录
            // // $upload->saveName = 'time';
            // // 上传文件 
            // $info   =   $upload->upload();
            // if(!$info) {
            // // 上传错误提示错误信息
            //     $ajaxdata['info'] = $upload->getError();
            //     $ajaxdata['status'] = 400;
            //     $this->ajaxReturn($ajaxdata);
            // }else{
            // // 上传成功
            //     foreach ($info as $key => $value) {
            //         $image = new \Think\Image();
            //         $image->open('./Public/Uploads/sub_imgs/' . $value['savename']);
            //         // $value['ext'] 图片后缀名
            //         $new_file_name = $this->getMillisecond() . '.' . $value['ext'];
            //         $image->save('./Public/Uploads/sub_imgs/' . $new_file_name);
            //         @unlink('./Public/Uploads/sub_imgs/' . $value['savename']);
            //         $img_arr[] = $new_file_name;
            //     }
            //     $ajaxdata['info'] = implode(',', $img_arr);
            //     $ajaxdata['status'] = 1;
            //     $this->ajaxReturn($ajaxdata);
            // }
        }catch (Exception $exc) {
            $ajaxdata['info'] = $exc->getMessage();
            $ajaxdata['status'] = 400;
            $this->ajaxReturn($ajaxdata);
        }
    }

    //接受一个参数，从服务器上删除一张图片
    public function uploadDelete(){
        $exist=false;
        $skey=I('session_key',false);
        if($skey===false){
            $id=I('id',false);
            if(!ic_isPosInt($id)){
                return;
            }
            else {
                $map=array('id'=>$id);
                $exist=M('bh_looks')->where($map)->find();
                if(!$exist){
                    return;
                }
                $ctime=$exist['create_time'];
            }
        }
        else {
            $ctime=$_SESSION[$skey."_time"];
        }

        $delName=I('realName',false);
        if($delName===false){
            return;
        }
        
        if($exist){
            //是来自编辑页面的删除，需要实时保存到数据表
            $oldNames=explode(",", $exist['sub_imgs']);
            $newNames=array();
            foreach ($oldNames as $key => $value) {
                if($value!=$delName){
                    $newNames[]=$value;
                }
            }
            $newNames=implode(",", $newNames);
            $data['update_time']=time();
            $data['sub_imgs'] = $newNames;
            M('bh_looks')->where($map)->save($data);
        }
        $this->delMulti($delName,$ctime);
        
    }

    private function delMulti($delName,$ctime){
        $serverPath=ic_getUploadImgServerPath("looks",$ctime);
        //当前栏目为造型，type=2
        $objType=2;
        //物理删除前先判断该图片是否被其它造型使用
        $picM=D('MultiUploadPic');
        $used=$picM->findUsedRecords($delName,$objType);
        if(!$used['used']){
            $serverPath=ic_getUploadImgServerPath("looks",$ctime);
            @unlink($serverPath.$delName);
            @unlink($serverPath."m_".$delName);
            @unlink($serverPath."s_".$delName);
            //删除批量图片表里的存储记录
            if($ctime==C("img_multi_create_time")){
                $umap=array('uni_name'=>$delName,'type'=>$objType);
                $aa=$picM->where($umap)->delete();
            }
        }
    }

    //从session取得旧图片信息并删除
    private function deleteOld(){
        $skey=I('session_key',false);
        if($skey===false){
            return;
        }
        $oldFiles=$_SESSION[$skey];
        if(!$oldFiles){
            return;
        }
        foreach ($oldFiles as $key => $value) {
            // $serverPath=ic_getUploadImgServerPath("looks",$_SESSION[$skey."_time"]);
            // @unlink($serverPath.$value['savename']);
            // @unlink($serverPath."m_".$value['savename']);
            // @unlink($serverPath."s_".$value['savename']);
            $this->delMulti($value['savename'],$_SESSION[$skey."_time"]);
        }
    }

    private function saveOldFIleSession($arr,$ctime){
        $skey=I('session_key',false);
        if($skey===false){
            return;
        }
        $_SESSION[$skey]=$arr;
        $_SESSION[$skey."_time"]=$ctime;
    }
    //更新规则
    public function updateRule() {
        try {
            // dump(I());exit;
                $ruleid = I('id');
                if (empty($ruleid)) {
                    $this->error('缺失主键');
                }
                $cate =I('cate',2);
                $label = I('type');
                $img =I('p_new_pic');
                $status = I('status');
                $name = I('aname');
                $memo = I('memo');
                $re_date=I('J-xl',false);
                $show_order=I('show_order',100);
                $sykh=I('sykh','');
                $xykh=I('xykh','');
                $pskh=I('pskh','');

                $calendarSM=D('Home/BHCalendar');
                $map = array();
                $map['id'] = $ruleid;
                $exist=M('bh_looks')->where($map)->find();
                if(!$exist){
                    // throw new Exception("待更新的造型已不存在，请回到列表页重新选择",1);
                    $this->error('待更新的造型已不存在，请回到列表页重新选择');
                }
                $saveData = array();
                // $saveData['cate'] = $cate;
                $saveData['label'] = $label;
                $saveData['status'] = $status;
                $saveData['img'] = $img;
                $saveData['item_ids'] = '';
                $saveData['name'] = $name;
                $saveData['memo'] = $memo;
                $saveData['update_time'] =time();
                $saveData['show_order'] =$show_order;
                $saveData['sykh'] = $sykh;
                $saveData['xykh'] = $xykh;
                $saveData['pskh'] = $pskh;
                // dump($saveData);exit;
                $flag = M('bh_looks')->where($map)->save($saveData);
                if ($flag) {
                    //如果制定了推荐日，则加入日历推荐表
                    if($re_date){
                        
                        $calendarSM->addrecommend($this->back_user_id,$re_date,$ruleid,$memo,$status,1);
                    }
                    else {
                        //提交时已无日期指定，则要把旧日期删掉
                        $calendarSM->deleteByLookId($exist['id']);
                    }
                    $this->success('造型编辑成功',ic_backToFormerPage(__APP__.'/Admin/Looks/index'));
                    // $this->success('造型编辑成功', '/Admin/Looks/index');

                } else {
                    // $this->error('造型编辑失败，可能未做修改');
                    $this->success('造型编辑成功',ic_backToFormerPage(__APP__.'/Admin/Looks/index'));
                }
            }catch (Exception $exc) {
                    $ajaxdata['info'] = $exc->getMessage();
                    $ajaxdata['status'] = 400;
                    $this->ajaxReturn($ajaxdata);
            }
    }

    // public function upload() {
    //     try {
    //         $img_arr = [];
    //         $upload = new \Think\Upload();// 实例化上传类
    //         $upload->maxSize   =     3145728 ;// 设置附件上传大小
    //         $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
    //         $upload->rootPath  =     './Public/Uploads/'; // 设置附件上传根目录
    //         $upload->savePath  =     ''; // 设置附件上传（子）目录
    //         $upload->autoSub  =     false; // 设置附件上传（子）目录
    //         // $upload->saveName = 'time';
    //         // 上传文件 
    //         $info   =   $upload->upload();
    //         if(!$info) {
    //         // 上传错误提示错误信息
    //             $ajaxdata['info'] = $upload->getError();
    //             $ajaxdata['status'] = 400;
    //             $this->ajaxReturn($ajaxdata);
    //         }else{
    //         // 上传成功
    //             foreach ($info as $key => $value) {
    //                 $image = new \Think\Image();
    //                 $image->open('./Public/Uploads/' . $value['savename']);
    //                 // $value['ext'] 图片后缀名
    //                 $new_file_name = $this->getMillisecond() . '.' . $value['ext'];
    //                 $image->save('./Public/Uploads/' . $new_file_name);
    //                 @unlink('./Public/Uploads/' . $value['savename']);
    //                 $img_arr[] = $new_file_name;
    //             }
    //             $ajaxdata['info'] = implode(',', $img_arr);
    //             $ajaxdata['status'] = 1;
    //             $this->ajaxReturn($ajaxdata);
    //         }
    //     }catch (Exception $exc) {
    //         $ajaxdata['info'] = $exc->getMessage();
    //         $ajaxdata['status'] = 400;
    //         $this->ajaxReturn($ajaxdata);
    //     }
    // }

    // public function getMillisecond() {
    //     list($t1, $t2) = explode(' ', microtime());
    //     return (float) sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    // }
    //添加规则
    public function addRule() {
        ic_rememberFormerPage();
        $this->new_type =M('bh_label');
        $dataListopt =$this->new_type->select();
        // dump($dataListopt);
        $this->assign('_listopt', $dataListopt);
        $this->assign('groupName', '造型管理');
        $this->assign('moduleName', '造型列表');
        $this->assign('actionName', '添加造型');
        $this->display('Looks:addRule');
    }
    //保存规则
    public function insertRule() {
        // var_dump(I());die;
        $uid = 999;
        $cate = I('cate');
        $type = I('type');
        $img = I('p_new_pic');
        $status = I('status');
        $name = I('name');
        $memo = I('memo');
        $re_date=I('J-xl',false);
        $show_order=I('show_order',100);
        $sykh=I('sykh','');
        $xykh=I('xykh','');
        $pskh=I('pskh','');
        $sub_imgs = I('new_img');

        $saveData = array();
        $saveData['uid'] = $uid;
        $saveData['cate'] = $cate;
        $saveData['label'] = $type;
        $saveData['img'] = $img;
        $saveData['status'] = $status;
        $saveData['name'] = $name;
        $saveData['memo'] = $memo;
        $saveData['item_ids'] = '';
        $saveData['create_time'] = time();
        $saveData['update_time'] = time();
        $saveData['show_order'] = $show_order;
        $saveData['sykh'] = $sykh;
        $saveData['xykh'] = $xykh;
        $saveData['pskh'] = $pskh;
        $saveData['sub_imgs'] = $sub_imgs;
        $flag = M('bh_looks')->add($saveData);

        if ($flag) {
            //如果制定了推荐日，则加入日历推荐表
            if($re_date){
                $calendarSM=D('Home/BHCalendar');
                $calendarSM->addrecommend($this->back_user_id,$re_date,$flag,$memo,$status,1);
            }
            $this->success('造型添加成功', ic_backToFormerPage(__CONTROLLER__ . '/index'));
        } else {
            $this->error('造型添加失败');
        }
    }
    //删除规则
    public function deleteRule() {
        ic_rememberFormerPage();
        $ruleid = I('id');
        if (empty($ruleid)) {
            $this->error('缺失主键');
        }
        //删除规则表
        $exist=M('bh_looks')->where("id={$ruleid}")->find();
        if(!$exist){
            $this->error('待删除造型未找到，请检查是否已删除.');
        }
        $flag = M('bh_looks')->where("id={$ruleid}")->delete();
        if ($flag) {
            //删除物理图片
            // $serverPath=ic_getUploadImgServerPath("looks",$exist['create_time']);
            $this->delMulti($exist['img'],$exist['create_time']);
            //如果有附图，附图也要删除
            if($exist['sub_imgs']){
                $arr= explode(",", $exist['sub_imgs']);
                foreach ($arr as $key => $value) {
                    $this->delMulti($value,$exist['create_time']);
                }
            }
            //2017-09-19 perry add 需把该造型对应的日历记录也删除
            M('bh_calendar')->where("look_id={$ruleid}")->delete();
            $this->success('造型删除成功',ic_backToFormerPage(__CONTROLLER__ . '/index'));
        } else {
            $this->error('造型删除失败');
        }
    }


    //根据上传的excel批量导入商品数据到表里
    public function ajaxImportMulti(){
        try {
            $ext = strrchr($_FILES["uploadExcelCommodityForm"]["name"], ".");
            if ($ext != ".xlsx")
                throw new \Exception('只允许上传xlsx类型的文件,请检查.');
            ini_set('memory_limit', '512M');
            //调用上传Excel表格数据
            $result = ic_uploadFile("xls,xlsx","looks",false);
            // dump($result);
            // exit;
            $uploadfile = $result[0]["savepath"] . $result[0]["savename"]; //获取上传路径文件名
            $startRow=3;
            $info = ic_importFromExcel($uploadfile,$startRow,"C","N"); //读取EXCEL表格
            if(!$info)
                throw new \Exception('未从上传文件中读取到数据，请检查');

            M()->startTrans();
            //数据准备
            $tm =M('bh_label');
            $cm=M('bh_looks');
            $mapto=array();
            $mapto['id']=array('neq', '1');
            $bhTypes =$tm->where($mapto)->field("id,name")->select();
            $cbhTypes=array();
            foreach ($bhTypes as $key => $value) {
                $cbhTypes[$value['name']]=$value;
            }
            $errMsg="";
            $succmsg="";
            $nl="\r\n";
            $picM=D('MultiUploadPic');
            $img_multi_hz=C('img_multi_hz_looks');
            $img_multi_create_time=C('img_multi_create_time');
            $datas=array();
            $noUniArr=array();
            $calendarSM=D('Home/BHCalendar');
            //开始插入或更新数据
            foreach ($info as $key => $value) {
                $c=array();
                //图片名作为唯一编号
                $c['ori_img']=$value[2];
                if(!ic_checkUnEmpty($c['ori_img'])){
                    $errMsg.=sprintf("第%d行造型合成图片名不能为空,请完善.%s",$startRow+$key,$nl);
                    //没有编号，直接中断
                    break;
                }
                if(array_key_exists($c['ori_img'], $noUniArr)){
                    $errMsg.=sprintf("第%d行和第%d行造型合成图片名重复了，请修改.%s",$startRow+$key,$noUniArr[$c['ori_img']],$nl);
                    //编号重复了
                    break;
                }
                $noUniArr[$c['ori_img']]=$startRow+$key;
                //本条数据是否标识为物理删除 N列
                $is_delete=$value[10];
                if(strtolower(trim($is_delete))=='y'){
                    $exist=$cm->where('ori_img="'.$c['ori_img'].'"')->find();
                    if(!$exist){
                        //$errMsg.=sprintf("第%d行编号%s指定删除，但系统中并无该数据，请检查.%s",$startRow+$key,$c['ori_img'],$nl);
                        //没有编号，直接中断
                        //break;
                        //没有找到待删除编号，continue
                        continue;
                    }
                    
                    //删除表数据
                    //删除造型数据
                    $afrow=$cm->where('id='.$exist['id'])->delete();
                    //需把该造型对应的日历记录也删除
                    $ruleid=$exist['id'];
                    M('bh_calendar')->where("look_id={$ruleid}")->delete();
                    //删除批量导入图片信息
                    $picM->where(array('ori_name'=>$exist['ori_img'].$img_multi_hz,'type'=>2))->delete();
                    if($afrow){
                        //删除物理图片
                        // $serverPath=ic_getUploadImgServerPath("looks",$exist['create_time']);
                        $this->delMulti($exist['img'],$exist['create_time']);
                        if(ic_checkUnEmpty($exist['sub_imgs'])){
                            $tmpsubArr=explode(",", $exist['sub_imgs']);
                            foreach ($tmpsubArr as $simg) {
                                $this->delMulti($simg,$exist['create_time']);
                            }
                        }
                    }
                    $succmsg.=sprintf("第%d行造型%s成功删除.%s",$startRow+$key,$exist['ori_img'],$nl);
                    continue;
                }
                
                $c['uid']=999;
                $c['cate']=2;
                $c['item_ids'] = '';
                //状态
                $status_str=(string)$value[3];
                if($status_str==="0"||$status_str==="1"||$status_str==="-1"){
                    $c['status']=$value[3];
                }
                else {
                    $c['status']=1;
                }

                //类型
                if(!array_key_exists($value[0],$cbhTypes )){
                    $errMsg.=sprintf("第%d行类型值不对,%s",$startRow+$key,$nl);
                    // continue;
                }
                else {
                    $c['label']=$cbhTypes[$value[0]]['id'];
                }
                //显示顺序
                $c['show_order']=$value[1];
                if(!ic_isPosInt($value[1] )){
                    $c['show_order']=1000;
                }

                //造型合成图
                if(ic_checkUnEmpty($value[2])){
                    $uploadedPic=$picM->getByOriName($value[2],2,$img_multi_hz);
                    if(!$uploadedPic){
                        $errMsg.=sprintf("第%d行造型合成图有指定:%s，但图未上传,%s",$startRow+$key,$value[2],$nl);
                        // continue;
                    }
                    else {
                        $c['img']=$uploadedPic['uni_name'];
                        $c['create_time']=$img_multi_create_time; //创建时间和图片上传时间一致，才能正确定位图片子目录ymd
                        $c['ori_img']=$value[2];
                    }
                }
                else {
                    $errMsg.=sprintf("第%d行造型合成图未指定，请补充%s",$startRow+$key,$nl);
                }


                //名称
                $c['name']=$value[4];
                //附注
                $c['memo']=$value[5];
                //上衣款号
                $c['sykh']=$value[6];
                
                //下衣款号
                $c['xykh']=$value[7];
                //配饰款号
                $c['pskh']=$value[8];
                if($errMsg!==''){
                    break;
                }
                //造型其它幅图   2017-12-11补加此功能
                if(ic_checkUnEmpty($value[11])){
                    $sub_imgs=explode(",", $value[11]);
                    $allGood=true;
                    $subArr=array();
                    foreach ($sub_imgs as $key2 => $value2) {
                        $uploadedPic=$picM->getByOriName($value2,2,$img_multi_hz);
                        if(!$uploadedPic){
                            $errMsg.=sprintf("第%d行造型副图有指定:%s，但图未上传,%s",$startRow+$key,$value2,$nl);
                            $allGood=false;
                            // continue;
                        }
                        else{
                            $subArr[]=$uploadedPic['uni_name'];
                        }
                    }
                    if($allGood){
                        $c['sub_imgs']=implode(",", $subArr);
                    }
                    
                }
                else {
                    $c['sub_imgs']="";
                }
                $c['update_time']=time();
                $datas[]=$c;

                $editMode='更新';
                $exist=$cm->field('id')->where('ori_img="'.$c['ori_img'].'"')->find();
                if(!$exist){
                    $editMode='新增';
                    $look_id=$cm->add($c);
                }
                else {
                    $look_id=$exist['id'];
                    $cm->where('id='.$look_id)->save($c);
                }


                

                //如果制定了推荐日，则加入日历推荐表
                $re_date=$value[9];
                if($re_date){
                    
                    $calendarSM->addrecommend($this->back_user_id,$re_date,$look_id,$c['memo'],$c['status'],1);
                }
                else {
                    //提交时已无日期指定，则要把旧日期删掉
                    $calendarSM->deleteByLookId($look_id);
                }

                
                $succmsg.=sprintf("第%d行造型%s成功%s.%s",$startRow+$key,$exist['ori_img'],$editMode,$nl);
            }
            //利用addAll第3参数特性，唯一键ori_img重复则更新，否则新增
            if($errMsg==''){
                // dump($datas);
                // exit;
                //$re=$cm->addAll($datas,array(),array('create_time','uid','cate','status','label','show_order','img','update_time','name','memo','sykh','xykh','pskh'));
                $logName='succ_'.time().".txt";
                file_put_contents(ic_getUploadImgServerPath('looks',false).$logName, $succmsg);
            }
            else {
                $logName=time().".txt";
                file_put_contents(ic_getUploadImgServerPath('looks',false).$logName, $errMsg);
                
                throw new \Exception(ic_getUploadImgFullPath('looks',$logName,false), -1);
                
            }
            M()->commit();
            $data['error'] = 'false';
            $data['msg'] =  ic_getUploadImgFullPath('looks',$logName,false);
            echo json_encode($data);
        } catch (\Exception $ex) {
            M()->rollback();
            $data['error'] = 'true';
            $data['msg'] = $ex->getMessage();
            echo json_encode($data);
        }
    }

    //批量上传多张图片第一步，把多张图片保存到服务器
    //返回服务器保存的新文件名和图片原文件名
    //，create_time必须写死才能找到正确子目录
    public function multiUploadPic(){
        $ctime=C('img_multi_create_time');
        try {
            //导入上传类
            $upload = new \Admin\ORG\UploadFileNew();
            //设置上传文件大小
            $upload->maxSize            = 200*1024*1024;
            //设置上传文件类型
            $upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
            //设置附件上传目录
            $upload->savePath           = ic_getUploadImgServerPath('looks',$ctime);
            //设置需要生成缩略图，仅对图像文件有效
            $upload->thumb              = true;
            // 设置引用图片类库包路径
            $upload->imageClassPath     = 'Think.ImageNew';
            //设置需要生成缩略图的文件后缀
            $upload->thumbPrefix        = 'm_,s_';  //生产2张缩略图
            //设置缩略图最大宽度
            $upload->thumbMaxWidth      = '600,300';
            //设置缩略图最大高度
            $upload->thumbMaxHeight     = '700,350';
            //设置上传文件规则
            $upload->saveRule           = 'uniqid';
            //删除原图
            $upload->thumbRemoveOrigin  = false;
            if (!$upload->upload()) {
                //捕获上传异常
                //$this->error($upload->getErrorMsg());
                //echo ($upload->getErrorMsg());
            } else {
                //取得成功上传的文件信息
                $uploadList = $upload->getUploadFileInfo();
                $img_arr=array();
                $img_arr_with_oriNmae=array();
                $datas=array();
                $uM=M('bh_multi_upload_pic');
                foreach ($uploadList as $key => $value) {
                    
                    $data=array();
                    $data['create_time']=time();
                    $data['update_time']=time();
                    $data['type']=2; //1代表commodity,2代表造型图
                    $data['ori_name']=$value['name'];
                    $data['uni_name']=$value['savename'];
                    //如果已存在则要把savename替换成和表里的uni_name一致
                    $umap=array('ori_name'=>$data['ori_name'],'type'=>$data['type']);
                    $existPic=$uM->where($umap)->find();
                    if($existPic){
                        $this->renameMulti(ic_getUploadImgServerPath('looks',$ctime),$data['uni_name'],$existPic['uni_name'],$ctime);
                        $value['savename']=$existPic['uni_name'];
                        // continue;
                        $data['uni_name']=$existPic['uni_name'];
                    }
                    $datas[]=$data;
                    $img_arr[]=$value['savename'];
                    $img_arr_with_oriNmae[]=$value['savename'];
                    $img_arr_with_oriNmae[]=$value['name'];
                }
                if($datas){
                    $flag=$uM->addAll($datas,array(),array('type','uni_name','update_time'));
                }
                //试着删除之前上传的旧图片
                $this->deleteOld();
                //保存当前图片信息到session
                $this->saveOldFIleSession($uploadList,$ctime);
                $ajaxdata['info'] = implode(',', $img_arr);
                $ajaxdata['infoMore'] = implode(',', $img_arr_with_oriNmae);
                
                $ajaxdata['status'] = 1;
                $this->ajaxReturn($ajaxdata);
                
            }
        }catch (Exception $exc) {
            $ajaxdata['info'] = $exc->getMessage();
            $ajaxdata['status'] = 400;
            $this->ajaxReturn($ajaxdata);
        }
    }

    //批量上传多张图片第二步，把多张已上传到服务器的文件名信息
    //批量插入或更新数据到eosi_bh_multi_upload_pic表
    public function multiUpload(){
        $this->success('批量导入图片成功', ic_backToFormerPage(__CONTROLLER__ . '/index'));
        // $new_img=I('new_img');                            //59ddc98c96ed4.JPG,59ddc98cedd88.JPG
        // $niarray=explode(",", $new_img);
        // $new_img_with_oriName=I('new_img_with_ori_name'); //59ddc98c40408.JPG,IMG_4200.JPG,59ddc98c96ed4.JPG,IMG_4404.JPG,59ddc98cedd88.JPG,IMG_4409.JPG
        // $niwoArr=explode(",", $new_img_with_oriName);
        // // dump($niwoArr);
        // $niwoArr2=array();
        // for($i=0;$i<=count($niwoArr)-2;$i+=2){
        //     $niwoArr2[$niwoArr[$i]]=$niwoArr[$i+1];
        // }
        // $mupicTypeSelect=I('mupicTypeSelect',2);
        // // dump($niwoArr2);
        // $datas=array();
        // $uM=M('bh_multi_upload_pic');
        // $ctime=C('img_multi_create_time');
        // foreach ($niarray as $key => $value) {
        //     $data=array();
        //     $data['type']=$mupicTypeSelect; //1代表commodity,2代表造型图
        //     $data['ori_name']=strtolower($niwoArr2[$value]);
        //     $data['uni_name']=$value;
        //     //到eosi_bh_multi_upload_pic判断同样name的图片是否存在，
        //     //如果已存在则要把savename替换成和表里的uni_name一致
        //     $umap=array('ori_name'=>$data['ori_name'],'type'=>$mupicTypeSelect);
        //     $existPic=$uM->where($umap)->find();
        //     if($existPic){
        //         $this->renameMulti(ic_getUploadImgServerPath('looks',$ctime),$data['uni_name'],$existPic['uni_name']);
        //         continue;
        //     }
        //     $data['create_time']=time();
        //     $data['update_time']=time();
        //     $datas[]=$data;
        // }
        // // dump($datas);
        // // exit;
        // $flag=true;
        // if($datas){
        //     $flag=$uM->addAll($datas,array(),array('type','uni_name','update_time'));
        // }
        // if ($flag) {
        //     // $this->success('规则添加成功', __CONTROLLER__ . '/rule'.'/id/'.$flag);
        //     $this->success('批量导入图片成功', ic_backToFormerPage(__CONTROLLER__ . '/index'));

        // } else {
        //     $this->error('批量导入图片失败');
        // }
    }
  
    //批量上传多张图片入口页
    public function multiuploadimg2(){
        $this->display();
    }

    //接受一个参数，从服务器上删除一张图片
    // public function uploadDelete(){
    //     $skey=I('session_key',false);
    //     if($skey===false){
    //         return;
    //     }
    //     else {
    //         $ctime=$_SESSION[$skey."_time"];
    //     }

    //     $delName=I('realName',false);
    //     if($delName===false){
    //         return;
    //     }
    //     $serverPath=ic_getUploadImgServerPath("looks",$ctime);
    //     $this->delMulti($serverPath,$delName);
    //     //删除批量图片表里的存储记录，如果有的话
    //     if(I('fromMultiUpload')==1){
    //         $uM=M('bh_multi_upload_pic');
    //         $umap=array('uni_name'=>$delName,'type'=>2);
    //         $aa=$uM->where($umap)->delete();
    //     }
    // }

       private function renameMulti($serverPath,$newName,$oldName,$ctime){
        $this->delMulti($oldName,$ctime);
        rename($serverPath.$newName, $serverPath.$oldName);
        rename($serverPath."m_".$newName, $serverPath."m_".$oldName);
        rename($serverPath."s_".$newName, $serverPath."s_".$oldName);
    }
}
